from telnetlib import *
import sys
import time
from mod_telnet import getch


class TelnetClient(Telnet):
    """
    TelnetClient base on built-in telnetlib
    TelnetClient.client() works like telnetlib.mt_interact but sends each char separately.
    Chars are caught using the getch method.client.client
    This class has been designed to work with Cisco devices console access through reverse telnet.
    """

    def client(self):
        """
        Multi-thread basic interactive telnet client.
        """
        import thread
        thread.start_new_thread(self.listenerTimed, ())
        while 1:
            # Sends one char at a time
            char = getch._Getch()
            if not char:
                break
            for i in xrange(sys.maxint):
                k=char()
                if k<>'':
                    break

            # Catching CTRL+Q to close telnet connection
            if k == '\x11':
                self.close()
                break

            # Catching broken pipe error
            try:
                self.write(k)
            except IOError:
                sys.stdout.write('\n')
                break

    def listenerTimed(self):
        """
        Helper for mt_interact() -- this executes in the other thread.
        Modified TelnetLib version, adding time.sleep to prevent 100% cpu usage
        when there's nothing waiting to be send to stdout
        """

        while 1:
            try:
                data = self.read_eager()
            except EOFError:
                #print '*** Connection closed by remote host ***'
                return
            if data:
                sys.stdout.write(data)
            else:
                sys.stdout.flush()
                time.sleep(0.1)

if __name__ == '__main__':
    print "TelnetClient Test..."
    tn = TelnetClient("10.254.0.99")
    tn.client()